import axios from 'axios'
import {getToken,getClientId} from '@/libs/util'
import config from '@/config'
import vue from "@/main";
const host = process.env.NODE_ENV === 'development' ? config.host.dev : config.host.pro

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Authorization' : 'Bearer ' + getToken(),
        'ClientId': getClientId()
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      return data
    }, error => {
      this.destroy(url)
      vue.$message.error('请检查网络连接')
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    if(options.ignoreBaseUrl){
      options.baseURL = ''
    }
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
